package net.tycmc.cty.ctyms.timejob.common;

import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.dao.BaseDAO;
import net.tycmc.bulb.common.datasource.ProxoolDataSource;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.dbutil.pager.Pager;
import net.tycmc.bulb.dbutil.pager.PagerModel;


public class MyBaseDAO {

	private BaseDAO baseDAO;

	
	
	private static String proxool = "proxool.test";
	
	public  MyBaseDAO() {
		baseDAO = new BaseDAO();
		ProxoolDataSource connGetter = new ProxoolDataSource();
		connGetter.setProxoolname(proxool);
		baseDAO.setConnGetter(connGetter);
	}
	
	/**
	 * @param baseDao the baseDao to set
	 */
	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public BaseDAO getBaseDAO() {
		return baseDAO;
	}
	/**
	 * 分页加载 
	 * @param strSQL
	 * @param params
	 * @param page
	 * @return
	 */
	public PagerModel getPager2015(String strSQL, Object[] params,Pager page,boolean flag){
		PagerModel pager=new PagerModel();
		//设置记录总数
		if(flag==false){//为false的时候，查询总条数，为true的时候，总条数由页面传递
			pager.setTotal(getTotal2008(strSQL,params));
		}
		//设置当前页显示数据
		pager.setDatas(getDatas2008(strSQL,params,page));
		return pager;
	}
	
	public List<Map<String,Object>> getDatas2008(String strSQL, Object[] params, Pager page) {
		int beginRow = 0;
		int endRow = 0;
		if(page==null){
			endRow = 100000000;
		}else{
			beginRow = page.getStart();
			endRow = page.getLength()+beginRow;
		}
		String resultSql = "";
		if(strSQL.indexOf("distinct")>-1){
			resultSql = (new StringBuilder("select * from (select row_number() over(order by tmp_id) rownum,* from (select distinct top ")).append(endRow).append(" tmp_id=0,").append(strSQL.replaceAll("distinct", "").substring(6)).append(") tab1 ) tab2 where rownum>").append(beginRow).toString();
		}else{
			resultSql = (new StringBuilder("select * from (select row_number() over(order by tmp_id) rownum,* from (select top ")).append(endRow).append(" tmp_id=0,").append(strSQL.substring(6)).append(") tab1 ) tab2 where rownum>").append(beginRow).toString();
		}		
		List<Map<String, Object>> datas = baseDAO.execQuery(resultSql, params);
		return datas;
	}

	private int getTotal2008(String strSQL, Object[] params) {
		String rowCountSql = "";
		if(strSQL.indexOf("distinct")>-1){
			rowCountSql = (new StringBuilder("select count(*)as counts from (select distinct top 100000000 ")).append(strSQL.replaceAll("distinct", "").substring(6)).append(") tab1").toString();
		}else{
			rowCountSql = (new StringBuilder("select count(*)as counts from (select top 100000000 ")).append(strSQL.substring(6)).append(") tab1").toString();
		}
		Map<String,Object> map = baseDAO.execQueryOne(rowCountSql, params);
		if(map!=null&&!MapGetter.getString(map, "counts").equals(""))
			return Integer.parseInt(MapGetter.getString(map, "counts"));
		return 0;
	}
}
